<template>
  <view class="page job-list rec-bag-pop-page">
    <uni-navbar 
      title="福利中心" 
      :border="false"
      :fixed="true"
      :height="barHeight"
      :rightWidth="60"
      :leftWidth="60"
      titleStyle="color:#fff;fontSize:18px;"
      bgColor="transparent"
      :placeholder="false"
      :autoBack="true"
    > 
      <view slot="left">
        <image v-if="!isMpAlipay && !isMpBaidu && !isMpToutiao" src="../../static/images/back_white2.png" class="back-icon" style="margin-left: -10rpx;"></image>
      </view>
    </uni-navbar>

    <scroll-view
      class="page-scroll-vi"
      :style="{paddingTop: headHt}"
      :scroll-y="true"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshTrigged"
      :refresher-threshold="100"
      refresher-background="transparent"
      @refresherrefresh="onPulling"
      @scrolltolower="pageScrollBottomEv"
    >
      <view class="con-list">
        <block v-if="jobList.length">
          <view
            v-for="(item, index) in jobList"
            :key="index"
            class="order-list-item flex items-start"
          >
            <view class="order-item-msg" @click="clickToJobDetail(item)">
              <view class="order-item-up flex items-center justify-between overflow-hidden font-b">
                <view class="order-item-title font16">
                  {{ item.title }}
                </view>
                <view class="nowrap cor-red" style="white-space: nowrap;">
                  <text class="font12">¥</text>
                  {{ item.salaryTxt }}/{{item.salaryUnit}}
                </view>
              </view>

              <view class="flex justify-between">
                <view class="row-welfare-wp" v-if="item.welfarelistnameArr && item.welfarelistnameArr.length">
                  <text v-for="(child, idx) in item.welfarelistnameArr" :key="idx" class="welfare-txt">
                    {{child}}
                  </text>
                </view>
                <view v-else></view>

                <view class="job-tp-row" v-if="actionType == 1 && !applySuccess">
                  <image :src="staticHost+'/coin.png'" mode="widthFix" style="width:38rpx;margin: 0 16rpx;"></image>
                  <text>+{{ formatGold(item.points) }} 金币</text>
                </view>
              </view>

              <view class="row-company">
                <view class="left-info">
                  <view :class="['avatar-s', item.cmpId > -1 ? 'company' :'']">
                    {{item.firstLetter}}
                  </view>
                  <text class="comp-name overflow-hidden">{{item.cmpName}}</text>
                </view>

                <view class="right-c">
                  <button v-if="actionType==1 || actionType==4" class="btn" >立即报名</button>
                  <template v-if="actionType==2">
                    <button v-if="isMpToutiao || isMpKuaishou || isMpWeixin" class="btn" open-type="share"
                    :data-id="item.id">去分享</button>
                    <button v-else class="btn" >去分享</button>
                  </template>
                  
                  <button v-if="actionType==3" 
                    :class="['btn' , item.isCompleted == 1 ? 'grey-btn':'' ]"
                  >
                    {{ item.isCompleted == 2 ? '去浏览':  item.isCompleted == 1 ? '已查看' : '查看职位'}}
                  </button>
                </view>
              </view>
            </view>
          </view>
          <view class="load-more">
            <u-loadmore :status="status" />
          </view>
        </block>
        <block v-if="!hasMoreData && !jobList.length">
          <view class="no-data">
            <view>{{noDataTxt}}</view>
          </view>
        </block>
      </view>
    </scroll-view>

    <u-popup
      v-model="isVisibleRecGold"
      class="rec-bag-pop"
      :border-radius="12"
      mode="center"
      :mask="true"
      style="backround:transparent;"
      @close="closeRecGoldDia"
    >
      <view :class="['relative', isMpKuaishou ? 'ks-rec-dia' : '']">
        <image :src="staticHost + '/rec_bag_success.png'" mode="widthFix"></image>
        <view class="flex items-center font18 font-medium justify-center absolute" style="top:94rpx;width:100%;">
          <image :src="staticHost +'/sign-seq.png'" mode="widthFix" style="width:32rpx;"></image>
          <text style="margin:0 32rpx;color:#660100;">签到成功</text>
          <image :src="staticHost +'/sign-seq.png'" mode="widthFix" style="width:32rpx;"></image>
        </view>
        <view class="absolute text-center" style="bottom:168rpx; width:100%;color:#C7372A;">
          <text style="font-size:64rpx;font-weight:600;margin-right:8rpx;">+{{ shareItem.golds }}</text>金币</view>
        <button class="pop-rec-btn" @tap="btnClickClose">立即收下</button>
      </view>
    </u-popup>
  </view>
</template>

<script>
// #ifdef H5
import native from '@/static/js/nativeApp';
// #endif
import { GetJobViewed, GetSignDetail, QueryJobViewList, StartView, EndView, FinishJobShare } from '@/pages/welfare/api/index';;
import statusBarInfo from '@/pages/welfare/mixins/statusBarInfo'
import { isH5, isMpWeixin, isMpAlipay, isMpBaidu, isMpKuaishou, isMpToutiao } from '@/utils/platform';
import { staticHost } from '@/setting';

let currentPage = 1;
let pageSize = 10;
let shareTimer;

export default {
  mixins: [ statusBarInfo ],
  data() {
    return {
      staticHost,
      isMpAlipay,
      isMpWeixin,
      isMpBaidu,
      isMpToutiao,
      isMpKuaishou,
      jobList: [],
      shareItem: {},
      detailId: '',
      hasMoreData: true,
      actionType: 0,
      viewJobIds: [],
      isVisibleRecGold: false,
      isRefreshTrigged: false,
      applySuccess : false,
      shareSuccess: false,
      isMpWeixinH5: false,
      firstDay: -1,
      status: 'loadmore',
      noDataTxt: '这里空空如也，啥都没有哦~'
    };
  },
  async onShareAppMessage(ev) {
    let _self = this;
    let shareItem;
    console.log('ev> ', ev);

    let id = ev.target?.dataset?.id 
    if (id) {
      shareItem = this.jobList.find(per => per.id == id)
      if(shareItem) {
        let golds = 0;
        if (this.actionType == 2 && !this.shareSuccess) {
          golds = 100;
        }
        shareItem.golds = golds;
        this.shareItem = shareItem;
      }
      console.log('find result> ', shareItem);
    } else {
      shareItem = this.shareItem;
    }

    if (shareItem) {
      console.log(shareItem.title, '::消息 ', _self.detailId);
      let desc = `${shareItem.jobTypeName}${shareItem.welfarelistname ? shareItem.welfarelistname :''}`
      if (isMpWeixin || isMpKuaishou) {
        shareTimer && clearTimeout(shareTimer)
        shareTimer = setTimeout(() => {
          _self.shareSuccessHandler(shareItem);
        }, 3000)
      }
      return {
        title: `${shareItem.title}`,
        desc, // 描述
        path: `pages/detail/index?pId=${shareItem.id}`,
        scene: 'WXSceneSession', // 抖音分享微信场景
        success(res) {
          _self.shareSuccessHandler(shareItem);
        },
        fail(res) {
          _self.$showToast(`分享失败`)
        },
      }
    }
    return {
      title: `自游赚兼职`,
      desc: '找兼职上自游赚【加薪秘籍.高薪行业.从业指南】', // 描述
      path: `pages/index/index`,
      scene: 'WXSceneSession', // 抖音分享微信场景
      success(res) {
        _self.$showToast(`分享成功`)
      },
      fail(res) {
        _self.$showToast(`分享失败`)
      },
    }
    

    
    
    
  },
  onLoad(options) {
    let _self = this;
    this.signId = options.signId;
    this.detailId = options.detailId;
    this.actionType = options.type;
    this.maxTimes = options.maxTimes;
    if (isMpAlipay) {
      my.hideShareMenu()
    }

    function ready() {
      console.log('ready 是否是小程序::', window.__wxjs_environment === 'miniprogram');
      if (window.__wxjs_environment === 'miniprogram') {
        // 是小程序环境
        _self.isMpWeixinH5 = true;
      }
    }
    if (isH5) {
      setTimeout(() => {
        if (!window.WeixinJSBridge || !window.WeixinJSBridge.invoke) {
          console.log('开始监听window.ev.WeixinJSBridgeReady');
          document.addEventListener('WeixinJSBridgeReady', ready, false)
        } else {
          ready()
        }
      }, 500)
    }
  },
  onUnload() {
    shareTimer && clearTimeout(shareTimer)
  },
  async onShow() {
    if (this.actionType == 3) {
      await this.homeInfo();
    } else {
      await this.getSignDetail();
    }
    this.refreshApplies();
  },
  methods: {
    shareSuccessHandler(shareItem) {
      this.$showToast(`分享success`)
      console.log(this.detailId, '区分下', shareItem);
      if (this.detailId && shareItem.golds > 0 && (isMpWeixin || isMpAlipay || isMpToutiao || isMpKuaishou)) {
        FinishJobShare({ 
          jobId: shareItem.id,
          detailId: this.detailId
        }).then(res => {
          if (res.code == 200) {
            this.$showToast(`分享成功`)
            this.shareSuccess = true;
            setTimeout(() => {
              this.isVisibleRecGold = true;
            }, 300)
          }
        })
      }
    },
    closeRecGoldDia() {
      this.isVisibleRecGold = false;
    },
    btnClickClose() {
      this.closeRecGoldDia();
      setTimeout(() => {
        uni.navigateBack({
          delta: 0
        });
      }, 300)
    },
    onPulling() {
      this.isRefreshTrigged = true
      this.refreshApplies();
    },
    pageScrollBottomEv(e) {
      this.loadMore();
    },
    async getSignDetail() {
      let res = await GetSignDetail({
        signId: this.signId
      })
      if (res.code == 200) {
        let { groupitemdetails, cmped, signIndex, first } = res.data;
        this.firstDay = first;
        if (signIndex == 1 && cmped) {
          this.shareSuccess = true;
          this.applySuccess = true;
        } else {
          groupitemdetails.forEach(per => {
            if (per.taskType == 2 && per.cmped) {
              this.shareSuccess = true;
            }
            if (per.taskType == 1 && per.cmped) {
              this.applySuccess = true;
            }
          })
        }
      }
    },
    async homeInfo() {
      let res = await GetJobViewed()
      if(res.code == 200) {
        this.viewJobIds = res.data;
      }
    },
    refreshApplies() {
      // 刷新页面数据
      currentPage = 1;
      this.fetchListData().then(data => {
        uni.hideLoading()
        var jobList = [];
        
        this.isRefreshTrigged = false
        if (data.records && data.records.length) {
          jobList = data.records || []
          var hasMoreData = true;
          if (jobList.length < pageSize) {
            hasMoreData = false
          } else {
            currentPage++;
          }
          this.setData({
            status: hasMoreData ? 'loadmore' : 'nomore',
            hasMoreData,
            jobList
          })
        } else {
          this.setData({
            status: 'nomore',
            hasMoreData: false,
            jobList
          })
        }
      }).catch(e => {
        uni.hideLoading()
        this.isRefreshTrigged = false
        uni.stopPullDownRefresh();
      }).finally((e) => {
        this.isRefreshTrigged = false;
        uni.hideLoading();
        uni.stopPullDownRefresh();
      })
    },
    loadMore() {
      if (!this.hasMoreData) {
        return
      }
      this.setData({
        status: 'loading',
      })
      this.fetchListData().then(data => {
        console.log('x333');
        if (data.records.length) {
          var jobList = this.jobList;
          data.records.forEach(per => {
            jobList.push(per)
          })
          var hasMoreData = true
          if (data.records.length < pageSize) {
            hasMoreData = false
          } else {
            currentPage++;
          }
          this.setData({
            status: hasMoreData ? 'loadmore' : 'nomore',
            hasMoreData,
            jobList
          })
        } else {
          this.setData({
            isLoadMore: false,
            status: 'nomore'
          })
        }
      })
    },
    // 获取job列表
    fetchListData() {
      return new Promise((resolve, reject) => {
        QueryJobViewList({
          "pageSize": pageSize,
          "page": currentPage
        }).then(res => {
          if (res.code == 200 && res.data) {
            let arr = res.data.records || []
            this.pages = res.data.pages || 1;

            arr.forEach(per => {
              per.firstLetter = per.cmpId == -1 ? '个' : '企'
              per.salaryTxt = this.formatSalary(per);

              if (per.regionName) {
                // 截取方式1
                per.regionName= per.regionName.replace(/(?:.*)(区)$/, (content, $1)=>{
                  return $1 ? content.substr(0, content.length -1) : content 
                })
              }
              let wels = per.welfarelistname;
              if (wels) {
                per.welfarelistnameArr = wels.split(',')
                if (per.welfarelistnameArr.length > 3 ) {
                  per.welfarelistnameArr.length = 3 
                }
              } else {
                per.welfarelistnameArr = []
              }
            })
            if (this.actionType == 3) {
              this.formatJobStatusList(arr);
            }
            resolve(res.data)
          } else {
            reject(res)
          }
        })
      });
    },
    formatSalary(item) {
      const { minSalary = 0, maxSalary = 0, salary = 0} = item
      if (salary > 0) {
        return salary / 100
      } else if (minSalary > 0 && maxSalary > 0) {
        return `${minSalary / 100} ~ ${maxSalary / 100}`
      } else if (minSalary > 0) {
        return `最少${minSalary / 100}`
      } else if (maxSalary > 0) {
        return `最多${maxSalary / 100}`
      }
      return ''
    },
    formatGold(points) {
      if (points > 1000) {
        if (this.firstDay == 1) {
          return 2000;
        }
        return 1000;
      } else if (points > 100 && points <= 1000) {
        return 1000;
      } else {
        return 100;
      }
    },
    clickToJobDetail(item) {
      let _self = this;

      if (this.actionType == 3) {
        this.toPreview(item);
      } else {
        console.log('>>>>===== ', item, 15, this.detailId, this.actionType);
        
        let golds = 0;
        if (this.actionType == 1 && !this.applySuccess) {
          golds = this.formatGold(item.points)
        } else if (this.actionType == 2 && !this.shareSuccess) {
          golds = 100;
        }

        if (isMpWeixin || isMpAlipay || isMpBaidu || isMpToutiao || isMpKuaishou) {
          if (this.actionType == 1) {
            this.$navigateTo(`/pages/detail/index?pId=${item.id}&seconds=15&detailId=${this.detailId}&type=${this.actionType}&golds=${golds}`)
          } else if (this.actionType == 2) {
            this.shareItem = Object.assign({ golds }, item);
            if (isMpToutiao || isMpKuaishou || isMpWeixin) {
              return;
            }
            // #ifdef MP-ALIPAY
            // eslint-disable-next-line no-undef
            my.showSharePanel()
            // #endif

            // #ifdef MP-BAIDU
            // eslint-disable-next-line no-undef
            swan.openShare({
              title: item.title,
              content: `${item.jobTypeName},${item.welfarelistname|| ''}`, // 描述
              path: `pages/detail/index?pId=${item.id}`,
              success() {
                _self.$showToast(`分享时间`)
                FinishJobShare({ 
                  jobId: item.id,
                  detailId: _self.detailId
                }).then(res => {
                  if (res.code == 200) {
                    _self.$showToast(`分享成功`)
                    _self.shareSuccess = true;
                    setTimeout(() => {
                      _self.isVisibleRecGold = true;
                    }, 300)
                  }
                })
              },
              fail() {
                console.log('失败');
              }
            })
            // #endif
          }
          return;
        } else if (this.isMpWeixinH5 && window.wx) {
          // H5通过jssdk携带支付参数跳转小程序页面
          let path = `/pages/jobs/detail`; 
          let uri = window.location.href.split('?')[0]; //获取当前url;

          if (this.actionType == 1) {  
            // url=${uri}
            path += `?url=${uri}&jobId=${item.id}&seconds=15&detailId=${this.detailId}&type=${this.actionType}&golds=${golds}`;
          }  else if (this.actionType == 2) {
            path += `?url=${uri}&jobId=${item.id}&seconds=15&detailId=${this.detailId}&type=${this.actionType}&golds=${golds}`;
          }
          console.log('page>> ', path);
          wx.miniProgram.navigateTo({
            url: path
          })
          return;
        }

        // #ifdef H5
        if (window.native.toNewJobDetail) {
          native.toNewJobDetail({jobId:item.id, seconds:15, detailId: this.detailId, type:this.actionType, golds}, (res) => {
            console.log('报名回调', _self.applySuccess, res);
            if (typeof res == 'string') {
              res = JSON.parse(res)
            }
            if (res && res.code == 200) {
              if (this.actionType == 1) {
                _self.applySuccess = true;
              } else if (this.actionType == 2) {
                _self.shareSuccess = true;
              }
            }
          })
        } else {
          native.toJobDetail(item.id, 15, this.detailId, this.actionType)
        }
        // #endif
      }
    },
    toPreview(item) {
      console.log('item ', item);
      if (item.isCompleted == 1 || item.isCompleted == 3) {
        if (isMpWeixin || isMpAlipay || isMpBaidu || isMpToutiao || isMpKuaishou) {
          this.$navigateTo(`/pages/detail/index?pId=${item.id}&detailId=-1&seconds=15&type=3&golds=0`)
          return;
        } else if(this.isMpWeixinH5 && window.wx) {
          // H5通过jssdk携带支付参数跳转小程序页面
          let path = `/pages/jobs/detail`; 
          let uri = window.location.href.split('?')[0]; //获取当前url;
          path += `?url=${uri}&jobId=${item.id}&seconds=15&detailId=-1&type=3&golds=0`;
          console.log('page>> ', path);
          wx.miniProgram.navigateTo({
            url: path
          })
          return;
        }
        // #ifdef H5
        if (window.native.toNewJobDetail) {
          native.toNewJobDetail({jobId:item.id, seconds:15, detailId: -1, type:3, golds: 0})
        } else {
          native.toJobDetail(item.id, 15, -1, 3)
        }
        // #endif
      } else {
        if (this.isQuering) {
          return
        }
        this.isQuering = true;
        StartView({
          jobId: item.id,
          detailId: this.detailId
        }).then(req => {
          setTimeout(() => {
            this.isQuering = false;
          }, 1000)
          if (req.code == 200 && req.data.detailId) {

            let callback = (res) => {
              // 完成职位浏览，需要刷新列表数据
              if (typeof res == 'string') {
                res = JSON.parse(res)
              }
              if (res && res.code == 200 && res.data ) {
                // window.appFinishedJobs.jobId = res.data.jobId 
                console.log('》》执行预览职位15秒钟完毕：：：：', res.data);
                EndView({
                  id: req.data.id
                }).then(res => {
                  if (res.code == 200) {
                    this.previewDone(res.data.jobId)
                  }
                })
              }
            }
            
            if (isMpWeixin || isMpAlipay || isMpBaidu || isMpToutiao || isMpKuaishou) {
              this.$navigateTo(`/pages/detail/index?pId=${item.id}&seconds=15&detailId=${req.data.id}&type=3&golds=100`)
              return;
            } else if(this.isMpWeixinH5 && wx && wx.miniProgram) {
              // H5通过jssdk携带支付参数跳转小程序页面
              let path = `/pages/jobs/detail`; 
              let uri = window.location.href.split('?')[0]; //获取当前url;
              path += `?url=${uri}&jobId=${item.id}&seconds=15&detailId=${req.data.id}&type=3&golds=100`;
              console.log('page>> ', path);
              wx.miniProgram.navigateTo({
                url: path
              })
              return;
            }
            // #ifdef H5
            if (window.native.toNewJobDetail) {
              native.toNewJobDetail({jobId: item.id, seconds:15, detailId: req.data.id, 
                type: 3, golds: 100}, callback)
            } else {
              native.toJobDetail(item.id, 15, req.data.detailId, 3, callback)
            }
            // #endif
          }
        })
      }
    },
    async previewDone(jobId) {
      let result = this.jobList.find(per => per.id == jobId)
      if (result) {
        result.isCompleted = true;
        await this.homeInfo();
        if (this.actionType == 3) {
          this.formatJobStatusList(this.jobList)
        }
      }
    },
    formatJobStatusList(list) {
      let viewJobIds = this.viewJobIds || [];
      let len = viewJobIds.length;
      let maxTimes = this.maxTimes || 5;
      list.forEach(per => {
        let result = viewJobIds.find(id => per.id == id);
        // isCompleted 1已查看  2去浏览  3查看职位
        if (len >= maxTimes) {
          if (result) {
            per.isCompleted = 1;
          } else {
            per.isCompleted = 3;
          }
        } else {
          if (result) {
            per.isCompleted = 1;
          } else {
            per.isCompleted = 2;
          }
        }
      })
    }
  },
};
</script>
<style lang="scss">
.job-list {
  position: relative;
  width: 100%;
  height: 100%;

  .overflow-hidden {
    overflow: hidden;
  }
  .nowrap {
    flex-wrap: nowrap;
  }
  
  .page-scroll-vi {
    position: relative;
    width: 100%;
    padding: 0 32rpx 40rpx;
    overflow-y: auto;
    background: linear-gradient(180deg,#f50,#F9EEE7);
    height: 100vh;
  }

  .con-list {
    background: #fff;
    border-radius:  32rpx;


    .row-welfare-wp {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      overflow: hidden;
      flex: 1;
      // height: 60rpx;

      .welfare-txt {
        background: #F6F7FC;
        color: $grey_color;
        font-size: 24rpx;
        padding: 4rpx 6rpx;
        border-radius: 4rpx;
        margin-right: 5rpx;
      }
    }
    .job-tp-row {
      min-width: 100px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      color: #F96A35;
      height: 60rpx;
    }

  .order-list-item {
    padding: 32rpx 32rpx 0 32rpx;

    .order-item-msg {
      display: flex;
      flex-direction: column;
      width: 100%;
      border-bottom: 1px solid #EAEBEF;
      padding-bottom: 32rpx;

      .order-item-title {
        padding-right: 16rpx;
        overflow: hidden;
        white-space: nowrap;
        text-overflow:ellipsis;
      }
    }
    .row-company {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .left-info {
        display: flex;
        align-items: center;
        overflow: hidden;
      }
      .avatar-s {
        background: #F58338;
        width: 40rpx;
        height: 40rpx;
        line-height: 40rpx;
        font-size: 24rpx;
        border-radius: 40rpx;
        color: #fff;
        text-align: center;
        margin-right: 12rpx;

        &.company {
          background: #0F8DFF;
        }
      }
      .right-c .btn {
        width: 144rpx;
        height: 64rpx;
        line-height: 64rpx;
        border-radius: 64rpx;
        text-align: center;
        background: linear-gradient(90deg, #F9503E 0%, #F65353 100%);
        color: #fff;
        font-size: 24rpx;
        padding: 0;

        &.grey-btn {
          background: #EAEBEF;
          color: $grey_color;
        }
      }
    }
  }
    
  .load-more {
    margin-top: 60rpx;
    margin-bottom: 80rpx;
  }

    .no-data {
      text-align: center;
      height: 100%;
      width: 100%;
      background-color: #fff;
      color: $grey_color;
      font-size: 26rpx;
    }
    .no-data image {
      width: 388rpx;
      margin-top: 125rpx;
      margin-bottom: 60rpx;
    }
  }
}
</style>
